package fitnesshub.config;

import fitnesshub.interceptor.JwtTokenAdminInterceptor;
import fitnesshub.interceptor.JwtTokenMemberInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 配置类，注册web层相关组件
 */
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    @Autowired
    private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;

    @Autowired
    private JwtTokenMemberInterceptor jwtTokenMemberInterceptor;

    /**
     * 注册自定义拦截器
     *
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("开始注册自定义拦截器...");

        // 注册管理端拦截器
        registry.addInterceptor(jwtTokenAdminInterceptor)
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin/login","/admin/logout");

        // 注册客户端拦截器
        registry.addInterceptor(jwtTokenMemberInterceptor)
                .addPathPatterns("/member/**")
                .excludePathPatterns("/member/login","/member/logout", "/member/register");
    }

    /**
     * 跨域规则
     * @param registry
     */
    public void addCorsMappings(CorsRegistry registry) {
        log.info("开始配置跨域规则");
        // 配置跨域规则
        registry.addMapping("/**")
                .allowedOriginPatterns("*")    // 允许所有来源
                .allowedMethods("GET","POST","PUT","DELETE","OPTIONS")  // 允许的方法
                .allowedHeaders("*")    // 允许所有的头部信息
                .maxAge(3600)   // 预检请求的有消息（秒）
                .allowCredentials(true);    // 允许cookie等验证
    }

    /**
     * 设置图片访问
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("开始配置图片访问url");
        /* 通过url访问项目外的目录图片*/
        // 改成自己的
        registry.addResourceHandler("/admin/**").addResourceLocations("file:/F:/xxx/img/admin/");
        registry.addResourceHandler("/member/**").addResourceLocations("file:/F:/xxx/img/member/");
        registry.addResourceHandler("/coach/**").addResourceLocations("file:/F:/xxx/img/coach/");
        registry.addResourceHandler("/equipment/**").addResourceLocations("file:/F:/xxx/img/equipment/");
        registry.addResourceHandler("/course/**").addResourceLocations("file:/F:/xxx/img/course/");
    }
}
